package com.sky.zero.utils;

import cn.hutool.core.util.StrUtil;
import com.sky.zero.common.generate.function.ClassField;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class FunctionUtil {

    public static <T> List<String> getFieldNames(List<ClassField<T>> fns) {
        // 从function取出序列化方法
        List<String> nameList = new ArrayList<>();
        try {
            for (ClassField<T> fn : fns) {
//                Method writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace");
//                // 从序列化方法取出序列化的lambda信息
//                writeReplaceMethod.setAccessible(true);
//                SerializedLambda serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(fn);
//                String name = serializedLambda.getImplMethodName().substring("get".length());
//                nameList.add(StrUtil.lowerFirst(name));
                nameList.add(getFieldName(fn));
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return nameList;
    }

    public static <T> String getFieldName(ClassField<T> fn) throws Exception {
        Method writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace");
        // 从序列化方法取出序列化的lambda信息
        writeReplaceMethod.setAccessible(true);
        SerializedLambda serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(fn);
        String name = serializedLambda.getImplMethodName().substring("get".length());
        return StrUtil.lowerFirst(name);
    }


    public static <T> Map<String, Object> filterMap(Map<String, Object> map, List<ClassField<T>> fns) {
        List<String> fieldNames = getFieldNames(fns);
        for (String name : fieldNames) {
            map.remove(name);
        }
        return map;
    }
}
